package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.constant.ConditionCacheConstant;
import com.itheima.sfbx.insurance.dto.ConditionVO;
import com.itheima.sfbx.insurance.enums.ConditionEnum;
import com.itheima.sfbx.insurance.mapper.ConditionMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.Condition;
import com.itheima.sfbx.insurance.pojo.InsuranceCondition;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.IConditionService;
import com.itheima.sfbx.insurance.service.IInsuranceConditionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：筛选项服务实现类
 */
@Slf4j
@Service
public class ConditionServiceImpl extends ServiceImpl<ConditionMapper, Condition> implements IConditionService {

    @Resource
    private ICategoryConditionService categoryConditionService;
    @Resource
    private IInsuranceConditionService insuranceConditionService;

    private LambdaQueryWrapper<Condition> queryWrapper(ConditionVO conditionVO) {
        LambdaQueryWrapper<Condition> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(conditionVO.getConditionKey()), Condition::getConditionKey, conditionVO.getConditionKey())
                .like(StrUtil.isNotBlank(conditionVO.getConditionKeyName()), Condition::getConditionKeyName, conditionVO.getConditionKeyName())
                .eq(StrUtil.isNotBlank(conditionVO.getDataState()), Condition::getDataState, conditionVO.getDataState());
        return lqw;
    }


    @Override
    @Cacheable(value = ConditionCacheConstant.PAGE,key = "#pageNum +'-'+#pageNum + '-'+#conditionVO.hashCode()")
    public Page<ConditionVO> findPage(ConditionVO conditionVO, int pageNum, int pageSize) {
        LambdaQueryWrapper<Condition> lqw = queryWrapper(conditionVO);
        Page<Condition> page = this.page(new Page<>(pageNum, pageSize), lqw);
        return BeanConv.toPage(page, ConditionVO.class);
    }

    @Override
    public ConditionVO findById(String conditionId) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    @Caching(put = @CachePut(value = ConditionCacheConstant.BASIC,key = "#result.id"),
            evict = {@CacheEvict(value = ConditionCacheConstant.PAGE,allEntries = true)
                    ,@CacheEvict(value = ConditionCacheConstant.LIST,allEntries = true)})
    public ConditionVO save(ConditionVO conditionVO) {
        Integer count = lambdaQuery().eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .eq(Condition::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if (count > 0) {
            log.error("筛选项已存在,保存失败：{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.SAVE_FAIL);
        }
        Condition bean = BeanConv.toBean(conditionVO, Condition.class);
        save(bean);
        return BeanConv.toBean(bean, ConditionVO.class);
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = ConditionCacheConstant.PAGE,allEntries = true)
            ,@CacheEvict(value = ConditionCacheConstant.LIST,allEntries = true)
            ,@CacheEvict(value = ConditionCacheConstant.BASIC,key = "#conditionVO.id")})
    public Boolean update(ConditionVO conditionVO) {
        //判断筛选项是否存在
        Condition condition = this.getById(conditionVO.getId());
        if (condition == null) {
            log.error("筛选项不存在,更新失败：{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }

        Integer count = this.lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .eq(Condition::getId, conditionVO.getConditionKey())
                .count();
        if (count > 0) {
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        Integer count1 = categoryConditionService.lambdaQuery()
                .eq(CategoryCondition::getConditionKey, conditionVO.getConditionKey())
                .count();
        Integer count2 = insuranceConditionService.lambdaQuery()
                .eq(InsuranceCondition::getConditionKey, conditionVO.getConditionKey())
                .count();
        if (count1 > 0 || count2 > 0){
            log.error("筛选项已存在,更新失败：{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }

        return updateById(BeanConv.toBean(conditionVO, Condition.class));
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = ConditionCacheConstant.PAGE,allEntries = true)
            ,@CacheEvict(value = ConditionCacheConstant.LIST,allEntries = true)
            ,@CacheEvict(value = ConditionCacheConstant.BASIC,allEntries = true)})
    public Boolean delete(String[] checkedIds) {
        List<String> ids = Arrays.asList(checkedIds);
        List<Condition> olds = this.listByIds(ids);
        if (CollUtil.isEmpty(olds)) {
            return true;
        }
        Set<String> keySet = olds.stream()
                .map(Condition::getConditionKey)
                .collect(Collectors.toSet());
        Integer count1 = insuranceConditionService.lambdaQuery()
                .in(InsuranceCondition::getConditionKey, keySet)
                .eq(InsuranceCondition::getDataState,"0")
                .count();
        Integer count2 = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getConditionKey, keySet)
                .eq(CategoryCondition::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被方案或分类关联，无法删除：{}",keySet);
            throw new ProjectException(ConditionEnum.DEL_FAIL);
        }
        return removeByIds(ids);
    }

    @Override
    @Cacheable(value = ConditionCacheConstant.LIST,key = "#conditonVO.hashCode()")
    @Transactional
    public List<ConditionVO> findList(ConditionVO conditionVO) {
        LambdaQueryWrapper<Condition> lqw = queryWrapper(conditionVO);
        List<Condition> list = this.list(lqw);
        return BeanConv.toBeanList(list, ConditionVO.class);
    }

    @Override
    @Cacheable(value = ConditionCacheConstant.LIST,key = "conditonVO.hashCode()")
    @Transactional
    public List<ConditionVO> findInConditionKeys(List<String> conditionKeys) {
        List<Condition> list = lambdaQuery()
                .eq(Condition::getConditionKey, conditionKeys)
                .eq(Condition::getDataState, SuperConstant.DATA_STATE_0)
                .list();
        return BeanConv.toBeanList(list, ConditionVO.class);
    }
}
